<?php

class AskController extends Controller
{
    public $layout = '//layouts/topColumn';

    public $menuList;

    public $menuitemName;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}
                     /**
	 * Declares class-based actions.
	 */
                    public function actions()
                    {
                            return array(
                                'captcha'=>array(
                                                        'class'=>'CCaptchaAction',
                                                        'backColor'=>0xFFFFFF,
                                                        'minLength'=>4,
                                                        'maxLength'=>4,
                                                        'testLimit'=>1, 
                                )
                            );
                    }
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view', 'captcha', 'islogin', 'hotAsk'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create', 'close','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete', 'replyAdmin'),
				'roles'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$ask = $this->loadModel($id);
        
        $askReply = $this->newAskReply($ask);

        $page = new CPagination($ask->floorsCount);
        $page->pageSize = 10;

        //访问统计
        $session = Yii::app()->session;
        if (!isset($session['askViewed_'. $id]))
        {
            $session['askViewed_'. $id] = $id;
            Ask::model()->updateCounters(array('hits' => 1), 'ask_id=:id', array(':id' => $id));
        }

        if ($_GET['page'] > 1)
        {
            $startPage = $_GET['page'] - 1;
        }
        else
        {
            $startPage = 0;
        }
        $ask->askReplies = array_slice($ask->askReplies, $startPage*$page->pageSize, $page->pageSize);  

        $this->render('view',array(
            'model'=>$ask,
            'page'=>$page,
            'askReply' => $askReply,
        ));

    }

                      /**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Ask;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Ask']))
		{
			$model->attributes=$_POST['Ask'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->ask_id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model = $this->loadModel($id);
        if (!Yii::app()->user->checkAccess('admin') && yii::app()->user->id != $model->user_id)
        {
            throw new CHttpException("你没有权限访问！");
        }

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Ask']))
		{
			$model->attributes=$_POST['Ask'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->ask_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$model=$this->loadModel($id);
        if(!yii::app()->user->checkAccess('admin') && $model->user_id != yii::app()->user->id)
        {
            throw new CHttpException("你没有权限访问！");
        }

        $replies = AskReply::model()->findAll('ask_id=:id', array(':id'=>$id));

        foreach($replies as $reply)
        {
            if ($reply->isFloor == 1)
            {
                AskReplyReply::model()->deleteAll('be_replied_id=:id', array(':id'=>$reply->reply_id));
            }

            AskReply::model()->deleteAll('ask_id=:id', array(':id'=>$id));
        }

		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
    {
        $title = null;
        if(isset($_GET['search']))
        {
            $title = $_GET['search'];
        }
        $dataProvider=new CActiveDataProvider('Ask',array(
            'criteria'=>array(
                'condition'=>"title like '%{$title}%'",
                'order'=>'createdOn DESC',
            ),
        ));
        $ask = new Ask;

        if (isset($_POST['Ask']) && !Yii::app()->user->isGuest)
        {
            $ask->attributes = $_POST['Ask'];
            if ($ask->save())
            {
                $this->redirect(array('ask/index'));
            }
        }
        else if (isset($_POST['Ask']) && Yii::app()->user->isGuest)
        {
            $this->redirect(array('site/login'), FALSE);
        }

		$this->render('index', array(
			'dataProvider'=>$dataProvider,
                                                                'model' => $ask,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
                                          if (!Yii::app()->user->checkAccess('admin'))
                                         {
                                             throw new CHttpException("你没有权限访问！");
                                          }
		$model=new Ask('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Ask']))
			$model->attributes=$_GET['Ask'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Ask the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Ask::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Ask $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='ask-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	/**
	*执行一个action前加载css与js
	* 
	* @author : Huang Yuetian
	* @date : 07/23/2014
	*/

	public function beforeAction($action)
	{
		Yii::app()->getClientScript()->registerCssFile(Yii::app()->baseUrl . '/css/ask.css');
		Yii::app()->getClientScript()->registerScriptFile(Yii::app()->baseUrl . '/js/ask.js');    
		return parent::beforeAction($action);
	}
	
	/**
	 *
	 *@author : Huang Yuetian
	 *@date : 07/24/2014
	 */
	protected function newAskReply($ask)
	{
		$replies=new AskReply;
                
		if(isset($_POST['ajax']) )
		{
			echo CActiveForm::validate($replies);
			Yii::app()->end();
		}
		if(isset($_POST['AskReply']) && !Yii::app()->user->isGuest)
		{
			$replies->attributes=$_POST['AskReply'];
                        
			if ($ask->addAskReply($replies))
                                                                {
                                                                     $floorReply = new AskReplyReply;
                                                                     
                                                                     $floorReply->reply_id = $replies->reply_id; 
                                                                     $floorReply->be_replied_id = $_POST['AskReply']['be_replied_id'];
                                                                     $floorReply->save();
                                                                     //更新回复数
                                                                     Ask::model()->updateCounters(array('replyCount' => 1), 'ask_id=:id', array(':id'=>$ask->ask_id));
                                                                     
                                                                     $replies = new AskReply;
                                                                }
                                                                
                                                                if ($replies->attributes->isFloor == 0)
                                                                {
                                                                    $replies = new AskReply;
                                                                }
		}
                                         else if (isset($_POST['AskReply']) && Yii::app()->user->isGuest)
                                         {
                                                                $this->redirect(array('site/login'));
                                         }
                                            
		return $replies;
	}
        
                    /*
                     * 判断是否登录
                     * @author : Huang Yuetian
                     * @date : 07/28/2014
                     */
                    public function actionIsLogin()
                    {
                        if (Yii::app()->user->isGuest)
                        {
                           echo "false";
                        }  
                        else
                        {
                            echo "true";
                        }
                        
                    }
                  
                    /**
                     * 显示热门问题
                     * @author : Huang Yuetian
                     * @date : 07/31/2014
                     */
                    public function actionHotAsk()
                    {
                        $dataProvider = new CActiveDataProvider('Ask');
                        
                        $dataProvider->setCriteria(array('order'=>'hits DESC , replyCount DESC'));
                        $dataProvider->setPagination(array('pageSize'=>15));
                        
                        $this->render('hotAsk', array(
                                'dataProvider'=>$dataProvider,
                        ));
                    }
                    /**
                     * 关闭问题
                     * 
                     * @author : Huang Yuetian
                     * @date : 08/01/2014
                     */
                    
                    public function actionClose($id)
                    {
                        $askInfo = Ask::model()->findByPk($id);
                        
                        $isOwner = ($askInfo->user_id == Yii::app()->user->id);
                        
                        if (Yii::app()->user->checkAccess('admin') || $isOwner)
                        {
                            Ask::model()->updateByPk($id, array('isClose'=>1));
                        }
                        $this->redirect(array('ask/view', 'id'=>$id));
                    }
                    
                    /**
                     * 管理一个问题的回复
                     * 
                     * @author : Huang Yuetian
                     * @date : 08/02/2014
                     */
                    public function actionReplyAdmin($id)
                    {
                        $replies = new CActiveDataProvider('AskReply');
                        
                        $replies->setCriteria(array(
                                'condition'=>'ask_id=:id',
                                'params'=>array(
                                        ':id'=>$id,
                                 ),
                        ));
                        
                        $this->render('replyAdmin', array(
                                'dataProvider'=>$replies,
                        ));
                    }
}
